import React, { PureComponent } from 'react';
import {
  View,
  Modal,
  WebView,
  StyleSheet,
  DeviceEventEmitter,
  Text,
} from 'react-native';
import ZlstIcon from './zlst-icons';
import Theme from '../native-base-theme/variables/commonColor';

export default class ReportForm extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {};
  }

  webLoad = () => {
    if (this.props.msgStrToWeb) {
      this.webview.postMessage(this.props.msgStrToWeb);
    }
  }

  webMessage = (event) => {
    if (this.props.handlerMsgFromWeb) {
      this.props.handlerMsgFromWeb(event.nativeEvent.data);
    }
  }

  showLoading = () => {
    DeviceEventEmitter.emit('showLoading', true);
  }

  hideLoading = () => {
    DeviceEventEmitter.emit('showLoading', false);
  }

  webViewLoadError = () => {
    this.props.hide();
  }

  webview

  render() {
    const {
      show, hide, uri, title,
    } = this.props;
    return (
      <Modal
        visible={show}
        animationType="none"
        transparent={false}
        onRequestClose={hide}
        style={styles.pageContanier}
        onShow={this.onShow}
      >
        <View style={styles.headerTitle}>
          <View style={{ padding: 5 }}>
            <ZlstIcon
              style={styles.backIcon}
              name="fanhui"
              size={20}
              color="#ffffff"
              onPress={hide}
            />
          </View>
          <Text style={styles.headerText}>{title || '报表'}</Text>
          <View style={styles.rightOperate} />
        </View>
        <WebView
          ref={webref => { this.webview = webref; }}
          javaScriptEnabled
          mixedContentMode="always"
          source={{
            uri,
            originWhitelist: ['*'],
          }}
          style={styles.webview}
          onMessage={this.webMessage}
          onLoad={this.webLoad}
          onLoadStart={this.showLoading}
          onLoadEnd={this.hideLoading}
          onError={this.webViewLoadError}
        />
      </Modal>
    );
  }
}

const styles = StyleSheet.create({
  pageContanier: {
    flex: 1,
    width: '100%',
    height: '100%',
  },
  webview: {
    flex: 1,
  },
  headerTitle: {
    display: 'flex',
    justifyContent: 'space-between',
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: Theme.myPrimary,
    padding: 10,
  },
  backIcon: {
    width: 24,
  },
  headerText: {
    color: '#ffffff',
    fontWeight: 'bold',
    fontSize: 18,
  },
  rightOperate: {
    width: 24,
  },
});
